﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
//using System.IO;
using System.Runtime.InteropServices;

public class MouseLocation : MonoBehaviour {
	
	[Flags]
    enum MouseEventFlag : uint
    {
        Move        = 0x0001,
        LeftDown    = 0x0002,
        LeftUp      = 0x0004,
        RightDown   = 0x0008,
        RightUp     = 0x0010,
        MiddleDown  = 0x0020,
        MiddleUp    = 0x0040,
        XDown       = 0x0080,
        XUp         = 0x0100,
        Wheel       = 0x0800,
        VirtualDesk = 0x4000,
        Absolute    = 0x8000
    }
	
	public struct Point{
		public int x;
		public int y;
	}
	
	[DllImport("user32.dll")] 
	public static extern System.IntPtr FindWindowEx(System.IntPtr parent,System.IntPtr childe,string strclass,string strname);
	
	[DllImport("user32.dll", CharSet = CharSet.Auto)]
	public static extern bool MoveWindow(IntPtr hWnd,int x,int y,int width,int height,bool repaint);
	
	//[DllImport("user32.dll", CharSet = CharSet.Auto)]
	//public static extern int SetWindowLong(IntPtr hWnd,int nIndex,int dwNewLong);
	
	[DllImport("user32.dll")]
	public static extern bool SetCursorPos(int x,int y);
	
	[DllImport("user32.dll")]
	public static extern bool GetCursorPos(ref Point lpPoint);
	public static Vector2 GetCursorPos(){
		Point pp = new Point();
		GetCursorPos(ref pp);
		return new Vector2(pp.x,pp.y);
	}
		
	[DllImport("user32.dll")]       
	static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
	
	/*
	[DllImport("user32.dll")]
	public static extern bool SetWindowPos(IntPtr hWnd,
		int hWndInsertAfter,
		int X,
		int Y,
		int cx,
		int cy,
		int uFlags
	);
		
	//   窗口置前   
	public static void SetWindowPos(IntPtr hWnd)
	{
	    SetWindowPos(hWnd,-1,0,0,0,0,3);
	}  */

	[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
	public static extern short GetKeyState(int keyCode);
	
	
	IntPtr windowPtr;
	
	int posLength;

	List<Vector2> mousePos;
	bool toolSwtich=false;

	
	// Use this for initialization
	void Awake(){
		
	}
	
	void Start () {
	//	windowPtr=FindWindowEx(System.IntPtr.Zero,System.IntPtr.Zero,null,"7omoToolKit");
	//	SetWindowLong(windowPtr,-16,369164288);   
	//	MoveWindow(windowPtr,Screen.currentResolution.width-150,0,150,300,false);
		LoadPrefs();
		StartCoroutine(toolIE());
	}
	
	void LoadPrefs(){
		if(PlayerPrefs.GetInt("PosLength")==0){
			Debug.Log("Not Set Any Nodes");
		}
		else{
			posLength=PlayerPrefs.GetInt("PosLength");
			mousePos=new List<Vector2>();
			for(int i=0;i<posLength;i++){
				mousePos.Add(ConvertType(PlayerPrefs.GetString("Nodes"+i)));
			}
			
		}
	}
	
	string ConvertType(Vector2 pos){
		return(pos.x+","+pos.y);
	}
	Vector2 ConvertType(string pos){
		string[] temp=pos.Split(',');
		return new Vector2(int.Parse(temp[0]),int.Parse(temp[1]));
	}
	
		
	void SavePrefs(){
		PlayerPrefs.DeleteAll();
		posLength=mousePos.Count;
		PlayerPrefs.SetInt("PosLength",posLength);
		for(int i=0;i<posLength;i++){
			PlayerPrefs.SetString("Nodes"+i,ConvertType(mousePos[i]));
		}
	}
	
	void Update(){
		if(Input.GetKeyDown(KeyCode.F6)){//切换tool开关//
			toolSwtich=!toolSwtich;
		}
		if(Input.GetKeyDown(KeyCode.Space)){//增加光标位置list//
			if(mousePos==null){
				mousePos=new List<Vector2>();
			}
			mousePos.Add(GetCursorPos());	
			SavePrefs();
		}
		if(Input.GetKeyDown(KeyCode.F12)||Input.GetMouseButtonDown(1)){
			Application.Quit();	
		}
		if(Input.GetKeyDown(KeyCode.Return)){
			toolSwtich=true;
			if(mousePos.Count>0){
				current=0;
				SetCursorPos(Mathf.RoundToInt(mousePos[current].x),Mathf.RoundToInt(mousePos[current].y));
				posTarget=mousePos[0];
			}	
		}
		
//		SetWindowPos(windowPtr);
	}

	int current=0;
	IEnumerator toolIE(){
		if(toolSwtich){
			mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
			mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
			if(mousePos!=null){
				SetCursorPos(Mathf.RoundToInt(mousePos[current].x),Mathf.RoundToInt(mousePos[current].y));
				posTarget=mousePos[current];
				current++;
				if(current>=mousePos.Count)
					current=0;
			}
		}

		yield return new WaitForSeconds(0.2f);
		StartCoroutine(toolIE());
	}
	
	Vector2 posTarget=new Vector2(0,0);
	Vector2 scroolPos=new Vector2(0,0);
	void OnGUI(){
		GUI.backgroundColor=Color.white;
		GUI.contentColor=Color.black;
		GUILayout.BeginVertical();

		if(GUILayout.Button("开启自动模拟")){
			toolSwtich=true;
			if(mousePos.Count>0){
				current=0;
				SetCursorPos(Mathf.RoundToInt(mousePos[current].x),Mathf.RoundToInt(mousePos[current].y));
				posTarget=mousePos[0];
			}
		}

		GUILayout.Label("按下空格记录鼠标位置");
		GUILayout.Space(20);
		GUILayout.Label("鼠标位置列表");
		if(mousePos!=null){
			scroolPos = GUILayout.BeginScrollView(scroolPos);
			for(int i=0;i<mousePos.Count;i++){
				GUILayout.BeginHorizontal();
				GUILayout.Label(ConvertType(mousePos[i]),GUILayout.Width(80));
				if(GUILayout.Button("-",GUILayout.Width(20))){
					mousePos.RemoveAt(i);
					SavePrefs();
				}
				GUILayout.EndHorizontal();
			}
			GUILayout.EndScrollView();
		}
		
		GUILayout.EndVertical();
		if(toolSwtich){
			if((GetCursorPos()-posTarget).magnitude>20)
				toolSwtich=false;
		}
		
		/*全局按键，用来在程序最小化时也能响应键盘操作
		if(GetKeyState(17)!=1)
			Debug.Log("ctrl down"+GetKeyState(17));
		if(GetKeyState(32)!=1)
			Debug.Log("space down"+GetKeyState(32));
		*/
	}
}
